package org.jeecg.modules.project.service.imp;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import org.jeecg.modules.project.service.LoginService;
import org.jeecg.modules.project.vo.LoginDto;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;

/**
 * @author Mr.Liu
 * @date 2024/05/15
 * @Description
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Override
    public String login(LoginDto loginDto, HttpServletResponse response) {

        String appid = "小程序id";	// 之前步骤提到的
        String appPrivateKey = "私钥";  // 之前步骤提到的

        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        certAlipayRequest.setAppId(appid);
        certAlipayRequest.setPrivateKey(appPrivateKey);
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset("utf-8");
        certAlipayRequest.setSignType("RSA2");

        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        certAlipayRequest.setCertPath(loader.getResource("").getPath() + "appCertPublicKey.crt");//应用公钥证书
        certAlipayRequest.setAlipayPublicCertPath(loader.getResource("").getPath() + "alipayCertPublicKey_RSA2.crt");//支付宝公钥证书
        certAlipayRequest.setRootCertPath(loader.getResource("").getPath() + "alipayRootCert.crt");//支付宝根证书

        try {
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
            request.setGrantType("grantType");
            request.setCode(loginDto.getCode());
            AlipaySystemOauthTokenResponse alipaySystemOauthTokenResponse = alipayClient.certificateExecute(request);
            if (alipaySystemOauthTokenResponse.isSuccess()) {
//                LogUtils.info("调用成功, Response result={}", alipaySystemOauthTokenResponse.getBody());
                // 生成UUID
                // String tokenId = UUID.randomUUID().toString().replaceAll("-", "");
                // 设置返回tokenid (用户id组成)
                // response.setHeader(TOKEN, JwtUtil.sign(alipaySystemOauthTokenResponse.getUserId(), tokenId));
                return alipaySystemOauthTokenResponse.getUserId();
            } else {
//                LogUtils.info("调用失败, {}", alipaySystemOauthTokenResponse.getSubMsg());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }


}
